package com.example.servlet;

import com.example.model.User;
import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/admin-user")
public class AdminUserServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");
        
        // 检查是否是管理员
        if (currentUser == null || !"admin".equals(currentUser.getUsername())) {
            response.sendRedirect("login.jsp");
            return;
        }
        
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT id, username, email, register_time, last_login_time, status FROM users ORDER BY register_time DESC";
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            
            List<User> users = new ArrayList<>();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setEmail(rs.getString("email"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
                user.setLastLoginTime(rs.getTimestamp("last_login_time"));
                user.setStatus(rs.getString("status"));
                users.add(user);
            }
            
            request.setAttribute("users", users);
            request.getRequestDispatcher("admin-user.jsp").forward(request, response);
            
        } catch (SQLException e) {
            e.printStackTrace();
            String errorMsg = "数据库连接错误";
            if (e.getMessage().contains("Table")&& e.getMessage().contains("doesn't exist")) {
                errorMsg = "数据库表不存在，请先初始化数据库。";
            } else if (e.getMessage().contains("Access denied")) {
                errorMsg = "数据库连接被拒绝，请检查用户名和密码。";
            } else if (e.getMessage().contains("Communications link failure")) {
                errorMsg = "无法连接到数据库服务器，请检查MySQL服务是否启动。";
            }
            request.setAttribute("error", errorMsg + ": " + e.getMessage());
            request.setAttribute("users", new ArrayList<>());
            request.getRequestDispatcher("admin-user.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
} 